package com.tpc.yaoxpt.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tpc.yaoxpt.main.LogModule;
import com.tpc.yaoxpt.main.MainController;
import com.tpc.yaoxpt.utils.FileUtil;
import com.tpc.yaoxpt.utils.HttpClientUtil;
import com.tpc.yaoxpt.utils.JDBCUtil;
import com.tpc.yaoxpt.utils.StringUtil;
import javafx.application.Platform;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.util.Map;

@Service
@Slf4j
public class InvoiceService {
    final LogModule logModule = LogModule.getInstance();
    public void invoice(){
        String intType = "C011";
        String intName = "配送订单";
        String url = FileUtil.getValue("PTCONFIG","URL");
        url = url + "v2/delv/drug/ship/commit";
        Connection connection = null;
        try {
            connection = JDBCUtil.getConnection();
            QueryRunner queryRunner = new QueryRunner();
            String tableName = FileUtil.getValue(intType,"TABLE");
            String getDataSql = "SELECT TOP 1 * FROM "+ tableName +" WHERE ISDONE ='N' ORDER BY COUNT";
            Map<String, Object> result = queryRunner.query(connection, getDataSql, new MapHandler());
            String valueInfo = JSON.toJSONString(result);
            if(valueInfo.equals("null")) {
//                logModule.appendLogInfo( "\n 【" + intType+"】 无上传订单！");
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        MainController.staticLogText.appendText("\n 【" + intType+"】 无上传订单！");
                    }
                });
                log.info("{}无上传订单！",intType);
                return;
            }
            JSONArray jsonArray = new JSONArray();

            JSONObject jsonObject = JSONObject.parseObject(valueInfo);
            jsonArray.add(jsonObject);
            JSONObject uploadData = new JSONObject();
            uploadData.put("list",uploadData);
            String returnInfo = HttpClientUtil.doPost(url, uploadData);
            JSONObject returnJSON = JSONObject.parseObject(returnInfo);
            String companyDistributeId =  jsonObject.getString("companyDistributeId");
            if(returnJSON.getString("returnCode").equals("1")){

            }
        }catch (Exception e){
//            logModule.appendLogInfo( "\n" + StringUtil.getErrorString(intType,intName,e.getMessage()));
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    MainController.staticLogText.appendText("\n" + StringUtil.getErrorString(intType,intName,e.getMessage()));
                }
            });
            e.printStackTrace();
        }finally {
            JDBCUtil.close(connection);
        }

    }
}
